package com.zoe.oauth2gitee.controller;

import com.google.gson.Gson;
import com.zoe.oauth2gitee.domain.AccessToken;
import com.zoe.oauth2gitee.domain.User;
import okhttp3.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author Zoe
 * @Date: 2021/03/04
 * @Description
 */
@Controller
@RequestMapping("/oauth")
public class HelloController {
    @Resource
    AccessToken accessToken;

    // 方式一: 1:前端点击授权链接,授权通过后,会访问这个接口
    // 2:接口内部获取code
    // 3:拿到code,再去换token
    // https://gitee.com/api/v5/oauth_do c#/list-item-1
    @GetMapping("/callback/gitee")
    public String callback(@RequestParam("code") String code, HttpServletRequest httpServletRequest) throws Exception {
        System.out.println("回调调用：code" + code);


        accessToken.setClient_id("570999a1aa8243fb3ccfe6cc05beee35a1b1299263bd7bbe39160b7392538540");
        accessToken.setClient_secret("485554480f1bec9a34dec02ddc4b0ac2d415f325b37d23866d59ce5dbdbe70da");
        accessToken.setRedirect_uri("http://localhost:8090/oauth/callback/gitee");
        accessToken.setCode(code);

        // 获取token
        getToken(accessToken);
        return "redirect:/";
    }

    // 方式二:
    // 1:通过浏览器直接输入http://localhost:8090/oauth/oauth
    // 2:内部重定向到授权的url
    // 3:授权成功后,应该会正常跳转到/callback/gitee这个接口,并拿到code码
    // 4:服务器内部拿到code码之后,再去换取token

    @GetMapping("/oauth")
    public void oauth(HttpServletResponse httpServletResponse) throws IOException {
        String url = "https://gitee.com/oauth/authorize?client_id=570999a1aa8243fb3ccfe6cc05beee35a1b1299263bd7bbe39160b7392538540&redirect_uri=http://localhost:8090/oauth/callback/gitee&response_type=code";
        httpServletResponse.sendRedirect(url);
    }

    // 获取token令牌
    public void getToken(AccessToken accessToken) throws Exception {
        String accessTokenJson = new Gson().toJson(accessToken);

        // okhttp请求发送post请求给码云认证服务器,获取token
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, accessTokenJson);
        Request request = new Request.Builder()
            .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + accessToken.getCode()
                + "&client_id=" + accessToken.getClient_id() + "" +
                "&redirect_uri=" + accessToken.getRedirect_uri() + "&client_secret=" + accessToken.getClient_secret())
            .post(body)
            .build();


        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            System.out.println(string + "   -------");

            // 获取授权的用户信息
            HashMap<String, String> hashMap = new Gson().fromJson(string, HashMap.class);
            String access_token = hashMap.get("access_token");
            System.out.println(access_token + "   -------");
            getUserInfo(access_token);
        }
    }

    // 获取用户信息
    public void getUserInfo(String token) throws Exception {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
            .url("https://gitee.com/api/v5/user?access_token=" + token)
            .build();

        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            System.out.println(string);
            User user = new Gson().fromJson(string, User.class);
            System.out.println(user.toString());
        }

    }
}
